package com.ld.poetry.aigc.iflycode.ningtw;

import com.ld.poetry.aigc.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CodeTranslateUtil {

    private static final String  SHEET_NAME="SHEET_NAME";

    public String compressFile(List<File> attachList, String zipFileName) {
        ZipOutputStream zos = null;
        InputStream ins = null;
        try {
            String tempFolderPath = "/tmp/";
            String zipFile = tempFolderPath + "/" + zipFileName;
            FileUtils.deleteFile(new File(zipFile));
            FileUtils.makeDir(new File(FileUtils.getFilePath(zipFile)));
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
//            zos.setEncoding("gbk");
            Map<String, Integer> duplication = new ConcurrentHashMap<String, Integer>();
            for (File attach : attachList) {
                String filePath = attach.getPath();
                // 通过 fileId 获取文件
                if (StringUtils.isEmpty(filePath)) {
//                    Long fileId = attach.getFileId();
//                    ins = getInputStreamByFileId(fileId);
                } else {// 通过 filePath 获取文件
//                    ins = getInputStreamByFilePath(filePath);
                }
                if (null == ins) {
                    continue;
                }
                String fileName = attach.getName();
                Integer num = 0;
                if (duplication.containsKey(fileName)) {
                    num = duplication.get(fileName) + 1;
                }
                duplication.put(fileName, num);

                StringBuilder strBuilder = new StringBuilder();
                if (num > 0) {
                    Integer index = fileName.lastIndexOf('.');
                    strBuilder.append(fileName.substring(0, index)).append("(").append(num).append(")")
                            .append(fileName.substring(index));
                    fileName = strBuilder.toString();
                }
                zos.putNextEntry(new ZipEntry(fileName));
                byte[] b = new byte[4096];
                int len = 0;
                while ((len = ins.read(b)) > 0) {
                    zos.write(b, 0, len);
                }
                zos.closeEntry();
                ins.close();
                ins = null;
            }
            zos.close();
            zos = null;
            return zipFile;
        } catch (Exception e) {
//            logger.error(e);
//            throw new Exception(ExceptionCode.WORD_DOWNLOAD_ERROR);
        } finally {
//            StreamUtil.closeOutputStream(zos, logger);
//            StreamUtil.closeInputStream(ins, logger);
        }
        return null;
    }



    /**
     *
     * @param formulaValue
     * @param amountValue
     * @return
     */
    public  static double calculate(String formulaValue,String amountValue){
        double retValue=0D;
        Workbook workbook=new HSSFWorkbook();
        try{
            FormulaEvaluator evaluator=workbook.getCreationHelper().createFormulaEvaluator();
            Sheet sheet=workbook.createSheet(SHEET_NAME);
            int rowCount=0;
            int cellCount=0;
            Row row=sheet.createRow(rowCount);
            Cell cell=row.createCell(cellCount);
            //先校验，避免如：2%3%这种会出现替换后变成2%*1003%*100
            int cellCountValidate=1;
            Cell cellValidate=row.createCell(cellCountValidate);
            cellValidate.setCellFormula(formulaValue);
            CellValue cellValueValidate=evaluator.evaluate(cellValidate);
            cellValueValidate.getNumberValue();
            //再真正计算
            String lastFormulaValue=formulaValue.replaceAll("%","%*"+amountValue);
            cell.setCellFormula(lastFormulaValue);
            CellValue cellValue=evaluator.evaluate(cell);
            retValue=cellValue.getNumberValue();
        }catch (Exception ex){
//            LogHelper.writeErrorLog(FormulaCalculateUtil.class,MODULE_NAME,"公式转换报错，公式："+formulaValue+",规模："+amountValue,MODULE_NAME,ex);
//            throw new BpmException("公式输入有误！");
        }finally {
            try {
                workbook.close();
            } catch (IOException e) {
//                LogHelper.writeErrorLog(FormulaCalculateUtil.class,MODULE_NAME,"关闭workbook报错",MODULE_NAME,e);
            }
        }
        return retValue;
    }

}
